package uit.comstore.model.blo;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import uit.comstore.model.entity.Category;
import uit.comstore.utils.HibernateSessionFactory;

public class CategoryBLO {
	@SuppressWarnings("unchecked")
	public List<Category> list() {
		List<Category> categories = null;
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();	
		session.beginTransaction();
		Query query = session.createQuery("from Category where status =:value");
		query.setParameter("value", 1);
		categories = query.list();
		session.getTransaction().commit();
		
		return categories;
	}

	public Category getById(Long id){
		Category category = null;
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();	
		session.beginTransaction();
		category = (Category) session.load(Category.class, id);
		session.getTransaction().commit();
		return category;
	}

	
	public Category add(Category category) {
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(category);
		session.getTransaction().commit();
		return category;
	}
	
	public Category delete(Long id) {
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Category category = (Category) session.load(Category.class, id);
		if(null != category) {
            session.delete(category);
        }
		session.getTransaction().commit();
		return category;
	}
	public Category update(Category c){
		Session session = HibernateSessionFactory.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.clear();
		Category category = (Category)session.get(Category.class, c.getId());	
		category.setName(c.getName());
		category.setStatus(c.getStatus());
		category.setParentId(c.getParentId());
		session.update(category);
		session.getTransaction().commit();
		session.close();
		return category;
	}
}
